import os
from django.http import Http404
import re
import codecs

#------------------------------------------------------------------------------

class LanguageFile():
    def __init__(self, path):
        self.path = path
    
    #--------------------------------------------------------------------------
    
    def get_language_name(self,country_code):
        """This is a routine to convert the country code to the language name
        Instead of this you could use a libary such as
        http://pypi.python.org/pypi/incf.countryutils/1.0"""
        
        country_code = country_code.upper()
        if country_code == "FR":
            return "French"
        elif country_code == "ES":
            return "Spanish"
        elif country_code == "IT":
            return "Italian"
        elif country_code == "DE":
            return "German"
        else:
            return "Unknown (%s)" % (country_code)
    
    #--------------------------------------------------------------------------
    
    def list_languages(self):
        """This routine will tell us what django languages use have po files for"""
        dir_list=os.listdir(self.path)
        country_list = []
        for dir in dir_list:
            if os.path.isdir(os.path.join(self.path, dir)):
                country_list.append({'code':dir,'name':self.get_language_name(dir)})
        return country_list
        
    #--------------------------------------------------------------------------
    
    def does_language_file_exist(self, language_code):
        """This routine will check to see if the folder of the given 
        language code exists"""
        language_code = language_code.upper()
        for language in self.list_languages():
            if language['code'].upper() == language_code:
                return True
        return False
    
    #--------------------------------------------------------------------------
    
    def get_filename(self, language_code):
        """ returns the filename for django.po """
        return "%s/%s/LC_MESSAGES/django.po" % (self.path,language_code)
    
    #--------------------------------------------------------------------------
    
    def load_django_po(self, language_code, line_number_required=0):
        """ Return a list of codes (msgid,msgstr) """
        if not self.does_language_file_exist(language_code):
            raise Http404
        f = codecs.open(self.get_filename(language_code), encoding='utf-8', mode='rb')
        section_list = []
        msgid = ""
        msgstr = ""
        codes = []
        line_number = 0
        held_line_number = 0
        process_section = False
        for line in f:
            line_number += 1
            if line_number_required > 0 and line_number_required != line_number and not process_section:
                continue
            process_section = True
            line = line.rstrip("\n")
            line = line.rstrip("\r")
            if line.startswith('#: '):
                if held_line_number == 0:
                    held_line_number = line_number
                section = line.lstrip("#: ").replace(".\\","")
                for m in re.finditer(r"(?P<filename>[^:]*):(?P<line_number>\d*)", section):
                    section_list.append({
                                'filename':m.group('filename'),
                                'line_number':m.group('line_number')})
            elif line.startswith('msgid "') and len(section_list) > 0:
                msgid = line.lstrip('msgid ').rstrip('"').lstrip('"')
            elif line.startswith('msgstr "') and len(section_list) > 0:
                msgstr = line.lstrip('msgstr ').rstrip('"').lstrip('"')
                codes.append({'section_list':section_list,
                            'msgid':msgid,
                            'msgstr':msgstr,
                            'line_number':held_line_number})
                held_line_number = 0
                section=""
                section_list=[]
                process_section = False
        f.close()
        return codes
        
    #--------------------------------------------------------------------------
    
    def write_django_po(self, language_code, replace_attr):
        if not self.does_language_file_exist(language_code):
            raise Http404
        f = codecs.open(self.get_filename(language_code), encoding='utf-8', mode='rb')
        lines = u""
        section = ""
        line_number = 0
        held_line_number = 0
        for line in f:
            line_number += 1
            line = line.rstrip("\n")
            line = line.rstrip("\r")
            if replace_attr.has_key(line_number):
                held_line_number = line_number
            elif line.startswith('msgstr "') and held_line_number > 0:
                line = 'msgstr "%s"' % (replace_attr[held_line_number])
                held_line_number = 0
            lines = lines + line + u'\n'
        f.close()
        f = codecs.open(self.get_filename(language_code), encoding='utf-8', mode='wb')
        f.write(lines)
        f.close()

#------------------------------------------------------------------------------

    